package com.hunttown.mes.manage.controller._basic;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.manage.cache.ManageRightRoleCacheData;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.AnalysisManageRightRoleAdminRelDTO;
import com.hunttown.mes.rpc.domain.AnalysisManageRightRoleDTO;
import com.hunttown.mes.rpc.domain.query.AnalysisManageRightRoleAdminRelDTOQuery;
import com.hunttown.mes.rpc.domain.query.AnalysisManageRightRoleDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.IpUtils;
import com.hunttown.mes.common.utils.JSONUtils;
import com.hunttown.mes.common.utils.SystemUtils;
import com.hunttown.mes.manage.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * @title: 角色管理
 * @author: wangjunfu
 * @date: 2018-10-26 15:14:22
 * @description:
 */
@Controller
@RequestMapping(value = "/basic/managerole")
public class ManageRoleController {

    private final static Logger logger = LoggerFactory.getLogger(ManageRoleController.class);

    private final AnalysisManageRightRoleManageService manageRightRoleService;
    private final AnalysisManageRightMenuManageService manageRightMenuService;
    private final AnalysisManageRightRoleMenuRelManageService rightRoleMenuRelService;
    private final AnalysisManageRightRoleAdminRelManageService roleAdminRelService;
    private final AnalysisManageManageService manageService;
    private final TransportOperateLogManageService logService;
    private final ModelService modelService;

    @Autowired
    public ManageRoleController(AnalysisManageRightRoleManageService manageRightRoleService, AnalysisManageRightMenuManageService manageRightMenuService, AnalysisManageRightRoleMenuRelManageService rightRoleMenuRelService, AnalysisManageRightRoleAdminRelManageService roleAdminRelService, AnalysisManageManageService manageService, TransportOperateLogManageService logService, ModelService modelService) {
        this.manageRightRoleService = manageRightRoleService;
        this.manageRightMenuService = manageRightMenuService;
        this.rightRoleMenuRelService = rightRoleMenuRelService;
        this.roleAdminRelService = roleAdminRelService;
        this.manageService = manageService;
        this.logService = logService;
        this.modelService = modelService;
    }

    //region 首页
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model, Integer id) {
        model.addAttribute("roleId", id);
        return "basic/managerole/index";
    }

    @RequestMapping(value = "/index_role", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, AnalysisManageRightRoleDTOQuery dtoQuery) {

        // 数据列表
        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO user = manageService.getFromCachePin(pin);
        if (user.getIsSuper() == 0) { //非管理员的情况下不显示管理员菜单
            dtoQuery.setIsSuperRole(0);
        }

        dtoQuery.setParentId(0);
        dtoQuery.setOrderBy("order by role_type desc, sort desc, id asc");

        Page<AnalysisManageRightRoleDTO> dataPage = manageRightRoleService.getForPage(dtoQuery);
        List<AnalysisManageRightRoleDTO> roleList = manageRightRoleService.getChildrenForEach(dataPage.getItems(), "|");

        for (AnalysisManageRightRoleDTO item : roleList) {
            //取出权限成员
            AnalysisManageRightRoleAdminRelDTOQuery query = new AnalysisManageRightRoleAdminRelDTOQuery();
            query.setRoleId(item.getId());
            query.setPageSize(1000);
            Page<AnalysisManageRightRoleAdminRelDTO> rolepage = roleAdminRelService.getForPage(query);

            //取出成员姓名
            List<String> names = new ArrayList<>();
            for (AnalysisManageRightRoleAdminRelDTO cli : rolepage.getItems()) {
                AnalysisManageDTO manage = manageService.getFromCacheId(cli.getAdminId());
                if (manage != null && manage.getStopFlag() == 0) {
                    names.add(manage.getNickName());
                }
            }
            item.setMembers(String.join("，", names));
        }

        model.addAttribute("roleList", roleList);
        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        return "basic/managerole/index_role";
    }

    // 左树
    @RequestMapping(value = "/left_tree", method = RequestMethod.POST)
    public String leftTree(Model model, Integer roleId) {
        if (roleId == null || roleId < 0) {
            roleId = 0;
        }
        List<String> menuList = manageRightMenuService.createCateTree(1, roleId);
        model.addAttribute("menuList", menuList);

        return "basic/managerole/left_tree";
    }
    //endregion

    //region 编辑
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String edit(Model model, Integer id, Integer parentId) {
        id = id == null ? 0 : id;
        parentId = parentId == null ? 0 : parentId;

        AnalysisManageRightRoleDTO obj = new AnalysisManageRightRoleDTO();
        obj.setId(id);
        obj.setParentId(parentId);
        obj.setRoleType(1);

        if (id > 0) {
            obj = manageRightRoleService.getById(id);
        }

        model.addAttribute("roleObj", obj);

        //获取上级权限
        AnalysisManageRightRoleDTOQuery query = new AnalysisManageRightRoleDTOQuery();
        query.setParentId(0);
        query.setPageSize(1000);
        Page<AnalysisManageRightRoleDTO> dataPage = manageRightRoleService.getForPage(query);
        model.addAttribute("rolePage", dataPage);

        return "basic/managerole/edit";
    }

    // 保存
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, AnalysisManageRightRoleDTO objDTO) {

        //结果返回，结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();
        try {
            String menuids = objDTO.getMenuIds();

            if (objDTO.getParentId() == null) {
                objDTO.setParentId(0);
            }
            if (objDTO.getIsSuperRole() == null) {
                objDTO.setIsSuperRole(0);
            }
            if (objDTO.getStopFlag() == null) {
                objDTO.setStopFlag(0);
            }

            //新增时检验是否唯一
            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                AnalysisManageRightRoleDTO obj = manageRightRoleService.getByRoleCode(objDTO.getRoleNameEn());
                if (obj != null && obj.getId() > 0) {
                    //说明已经有此记录了，不能插入。
                    map = OperateCode.CompositionResult(map, -10, "此角色名称已存在，请重新输入！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //设置初始值
            objDTO.setLastUpdatePeople(AdminBaseClass.getPin(request));
            objDTO.setLastUpdateTime(new Date());

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                objDTO = manageRightRoleService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            } else {
                //更新
                //将不需要更新的字段设置为NULL
                //objDTO.setRoleNameEn(null); //可以修改

                Boolean isNext = manageRightRoleService.updateInfoById(objDTO);
                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //删除旧权限（直接物理删除，否则数量量会越来越多）
            rightRoleMenuRelService.deletePysical(objDTO.getId());

            //保存新权限
            rightRoleMenuRelService.insrtForBatch(objDTO.getId(), menuids);

            // 删除用户-权限-菜单 缓存
            manageService.deleteManagerRoleMenuCache();

            //刷新角色缓存
            ManageRightRoleCacheData.init();

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            map.put("id", objDTO.getId().toString());
            map.put("parentId", objDTO.getParentId().toString());

            result = JSONUtils.toJSON(map);
            return result;
        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return json
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(HttpServletRequest request, Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = manageRightRoleService.delete(id);

            if (isNext) {
                //删除权限关联表中数据
                rightRoleMenuRelService.deletePysical(id);
            }

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 19, id, 4,
                    "删除权限角色信息",
                    "权限角色删除：" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    //endregion

    //region 启用禁用
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(Integer id, Integer status) {
        //结果返回，结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = manageRightRoleService.changeState(id, status);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion
}